<?php
class Validate extends Validate_Abstract
{
	protected $_messages;
	
	protected $_rules;
	
	public function __construct($locale = 'pt_BR')
	{
		$valFile = APPLICATION_PATH.'/configs/validation.ini';
		$valFile = new Zend_Config_Ini($valFile, $locale);

		$this->_messages = $valFile->toArray();
	}
	
	public function setRules($fromIni, $fromForm)
	{
		if(!$fromIni) {
			$this->_rules = $fromForm;
		} else {
			$list = array();

			foreach($fromIni as $column => $rule) {
				$rules = explode('|', trim($rule));

				foreach($rules as $param) {
					if(preg_match('/\[(.+|)\]/', $param)) {
						list($type, $params) = explode('[', $param);
						$params = rtrim($params, ']');
						$params = explode(',', $params);
						
						foreach($params as &$str) {
							$str = trim($str);
						}
						
						$list[$column][$type] = $params;
						continue;
					}
					$list[$column][$param][] = false;
				}
			}

			$this->_rules = $this->_mergeRules($list, $fromForm);
		}
		
		return $this;
	}
	
	public function check($values)
	{
		$result = array();
		
		foreach($values as $column => $value) {
			if(isset($this->_rules[$column])) {
				foreach($this->_rules[$column] as $type => $params) {
					if(!$this->$type(trim($value), $params)) {
						$message = $this->_messages['error'][$type];
						
						foreach($params as $param) {
							$message = str_replace('[#]', $param, $message);
						}
						
						$result[$column][$type] = $message;
					}
				}
			}
		}
		
		// Fields that don't came on the post
		$rest = array_diff_key($this->_rules, $values);
		foreach(array_keys($rest) as $column) {
			$message = $this->_messages['error']['required'];

			foreach($params as $param) {
				$message = str_replace('[#]', $param, $message);
			}
			
			$result[$column]['required'] = $message;
		}
		
		return $result;
	}
	
	/**
	 *	Walk through the rules adding if don't exist or keeping the preference
	 *	value
	 * 
	 * @param array $preference Values that will have preference in twice case
	 * @param array $second Values to add on the first argument
	 * @return array
	 */
	protected function _mergeRules($preference = array(), $second = array())
	{
		foreach($second as $column => $rules) {
			foreach($rules as $rule => $params) {
				if(!isset($preference[$column][$rule])) {
					$preference[$column][$rule] = $params;
				}
			}
		}
		
		return $preference;
	}
}